package com.cunjiankang.ui;

import android.app.Dialog;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.*;
import com.android.volley.*;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cunjiankang.R;
import com.cunjiankang.adapter.McInfoAdapter;
import com.cunjiankang.adapter.ScoreAdapter;
import com.cunjiankang.bean.request.BaseRequest;
import com.cunjiankang.bean.request.DrugDescRequest;
import com.cunjiankang.bean.response.BaseResponse;
import com.cunjiankang.bean.response.DrugDescResponse;
import com.cunjiankang.bean.response.ScoreResponse;
import com.cunjiankang.bean.vo.ShopRecord;
import com.cunjiankang.util.Contants;
import com.cunjiankang.util.HttpUtil;
import com.cunjiankang.util.PreferenceUtil;
import com.cunjiankang.util.TextViewUtil;
import com.cunjiankang.view.CustomProgressDialog;
import com.google.gson.Gson;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.SystemTool;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RecordActivity extends BaseActivity implements OnClickListener {

	@BindView(id = R.id.img_close, click = true)
	private ImageView imgClose;
	@BindView(id = R.id.layout_tip_content)
	public View tipContent;
	@BindView(id = R.id.detail_list)
	private ListView listView;
	@BindView(id = R.id.no_data)
	private TextView noData;
	@BindView(id = R.id.btn_back, click = true)
	private Button btnBack;
	@BindView(id = R.id.tv_info)
	private TextView tvInfo;
	@BindView(id = R.id.layout_content)
	private View layoutContent;
	@BindView(id = R.id.list_view)
	private ListView detailListView;
	
	private List<ShopRecord> list;
	private ScoreAdapter adapter;

	private RequestQueue mRequestQueue;
	private String url;
	private Dialog dialog;
	private boolean queryOk;
	

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_record);
		mRequestQueue = Volley.newRequestQueue(this);
		super.setRootView();
	}

	@Override
	public void initWidget() {
		super.initWidget();
		listView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Contants.starTime = System.currentTimeMillis();
				return false;
			}
		});
	}

	@Override
	public void initData() {
		super.initData();

		String username = PreferenceUtil.readString(RecordActivity.this, Contants.SP.username);
		String je="0";
		TextViewUtil textViewUtil = new TextViewUtil();

		float price = Float.parseFloat(je);
		DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
		je=decimalFormat.format(price);

		if (je.equals(".00")) {
			je = "0.00";
		}

		String info = String.format(getString(R.string.user_jr), username,je);
		int start1 = info.indexOf(username);
		int end1 = start1 + username.length();
		int start2 = info.indexOf(je);
		int end2 = start2 + je.length();
		tvInfo.setText(textViewUtil.getForegroundColorSpan(RecordActivity.this, info, start1,
				end1, start2, end2, "#e95013"));

		
		String ip = PreferenceUtil.readString(this, Contants.SP.local_ip);
		String port = PreferenceUtil.readString(this, Contants.SP.local_port);
		url = Contants.api_url;
		dialog = CustomProgressDialog.createDialog(this)
				.setMessage(R.string.loading);
		queryConsume();
		queryList();
	}
	
	private void queryList(){
		final BaseRequest request = new BaseRequest();
		request.type = Contants.ApiKey.userconsume;
		request.cardnum = PreferenceUtil.readString(this, Contants.SP.cardnum,"");
		request.group_id = PreferenceUtil.readString(this, Contants.SP.local_grubid);
		HttpUtil.postByLocal(RecordActivity.this,url, request, new HttpCallBack() {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				KJLoger.debug(request.type + ":" + t);
				try {
					ScoreResponse response = new Gson().fromJson(t,
							ScoreResponse.class);
					list = response.array;
					if (list != null && list.size() > 0) {
						adapter = new ScoreAdapter(RecordActivity.this, list);
						listView.setAdapter(adapter);
						listView.setVisibility(View.VISIBLE);
						noData.setVisibility(View.GONE);
					} else {
						noData.setVisibility(View.VISIBLE);
						listView.setVisibility(View.GONE);
					}
				} catch (Exception e) {
					String username = PreferenceUtil.readString(RecordActivity.this, Contants.SP.username);
					String je="0";
					TextViewUtil textViewUtil = new TextViewUtil();

					float price = Float.parseFloat(je);
					DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
					je=decimalFormat.format(price);

					if (je.equals(".00")) {
						je = "0.00";
					}

					String info = String.format(getString(R.string.user_jr), username,je);
					int start1 = info.indexOf(username);
					int end1 = start1 + username.length();
					int start2 = info.indexOf(je);
					int end2 = start2 + je.length();
					tvInfo.setText(textViewUtil.getForegroundColorSpan(RecordActivity.this, info, start1,
							end1, start2, end2, "#e95013"));
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				KJLoger.debug(request.type + ":" + t.toString());
				if (Contants.debug) {
					String resp = "{\"type\":\"userconsume\",\"array\":[{\"lshh\":\"P04F0700006554\",\"rq\":\"2014-04-28\",\"ontime\":\"15:36:00\",\"zje\":\"182.3544\"}]}";
					ScoreResponse response = new Gson().fromJson(resp,
							ScoreResponse.class);
					list = response.array;
					adapter = new ScoreAdapter(RecordActivity.this, list);
					listView.setAdapter(adapter);
					listView.setVisibility(View.VISIBLE);
				} else {
					noData.setVisibility(View.VISIBLE);
					listView.setVisibility(View.GONE);
					if (SystemTool.checkNet(RecordActivity.this)) {

					} else {
						ViewInject.toast(getString(R.string.net_error));
					}
				}

				String username = PreferenceUtil.readString(RecordActivity.this, Contants.SP.username);
				String je="0";
				TextViewUtil textViewUtil = new TextViewUtil();

				float price = Float.parseFloat(je);
				DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
				je=decimalFormat.format(price);

				if (je.equals(".00")) {
					je = "0.00";
				}

				String info = String.format(getString(R.string.user_jr), username,je);
				int start1 = info.indexOf(username);
				int end1 = start1 + username.length();
				int start2 = info.indexOf(je);
				int end2 = start2 + je.length();
				tvInfo.setText(textViewUtil.getForegroundColorSpan(RecordActivity.this, info, start1,
						end1, start2, end2, "#e95013"));
			}

			@Override
			public void onFinish() {
				super.onFinish();
				layoutContent.setVisibility(View.VISIBLE);
				dialog.dismiss();
				queryOk=true;
			}
		});
	}
	
	private void queryConsume(){
		final BaseRequest request = new BaseRequest();
		request.type = Contants.ApiKey.consume;
		request.cardnum = PreferenceUtil.readString(this, Contants.SP.cardnum,"");
		request.group_id = PreferenceUtil.readString(this, Contants.SP.local_grubid);
		dialog.show();
		HttpUtil.postByLocal(RecordActivity.this,url, request, new HttpCallBack() {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				KJLoger.debug(request.type + ":" + t);
				BaseResponse response = new Gson().fromJson(t,BaseResponse.class);
				if (response.flag.equals(BaseResponse.flag_success)) {
					String username = PreferenceUtil.readString(RecordActivity.this, Contants.SP.username);
					String je=response.je;
					TextViewUtil textViewUtil = new TextViewUtil();

					float price = Float.parseFloat(je);
					DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
					je=decimalFormat.format(price);

					if (je.equals(".00")) {
						je = "0.00";
					}

					String info = String.format(getString(R.string.user_jr), username,je);
					int start1 = info.indexOf(username);
					int end1 = start1 + username.length();
					int start2 = info.indexOf(je);
					int end2 = start2 + je.length();
					tvInfo.setText(textViewUtil.getForegroundColorSpan(RecordActivity.this, info, start1,
							end1, start2, end2, "#e95013"));
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				KJLoger.debug(request.type + ":" + strMsg);
				if (Contants.debug) {
					String username ="test";
					String je="182.3034";
					TextViewUtil textViewUtil = new TextViewUtil();
					String info = String.format(getString(R.string.user_jr), username,je);
					int start1 = info.indexOf(username);
					int end1 = start1 + username.length();
					int start2 = info.indexOf(je);
					int end2 = start2 + je.length();
					tvInfo.setText(textViewUtil.getForegroundColorSpan(RecordActivity.this, info, start1,
							end1, start2, end2, "#e95013"));
				}
			}

			@Override
			public void onFinish() {
				super.onFinish();
				if(queryOk){
					dialog.dismiss();
				}
				queryOk=true;
			}
		});
	}

	public void queryDesc(final String lshh) {
		dialog.show();
		StringRequest stringRequest = new StringRequest(Method.POST,url, new Listener<String>() {

					@Override
					public void onResponse(String response) {
						KJLoger.debug(response);
						dialog.dismiss();
						DrugDescResponse descResponse = new Gson().fromJson(
								response, DrugDescResponse.class);
						if (descResponse.flag.equals(BaseResponse.flag_success)) {
							if(descResponse.array!=null&&descResponse.array.size()>0){
								McInfoAdapter adapter=new McInfoAdapter(RecordActivity.this, descResponse.array);
								detailListView.setAdapter(adapter);
								tipContent.setVisibility(View.VISIBLE);
							}else{
								Toast.makeText(RecordActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
							}
						}else{
							Toast.makeText(RecordActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						dialog.dismiss();
						if(Contants.debug){
							String json="{\"type\":\"userconsume\",\"array\":[{\"spmch\":\"白芍\",\"shpgg\":\"135g*16\",\"dw\":\"克\",\"sshje\":\"7.44555\",\"shl\":\"10.0545\"}]}";
							DrugDescResponse descResponse=new Gson().fromJson(json, DrugDescResponse.class);
							McInfoAdapter adapter=new McInfoAdapter(RecordActivity.this, descResponse.array);
							detailListView.setAdapter(adapter);
							tipContent.setVisibility(View.VISIBLE);
						}else{
							if (SystemTool.checkNet(RecordActivity.this)) {
								
							} else {
								ViewInject.toast(getString(R.string.net_error));
							}
						}
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				DrugDescRequest descRequest = new DrugDescRequest();
				descRequest.type = Contants.ApiKey.userconsumedetail;
				descRequest.group_id = PreferenceUtil.readString(RecordActivity.this, Contants.SP.local_grubid);
				descRequest.lshh=lshh;
				descRequest.cardnum = PreferenceUtil.readString(RecordActivity.this,Contants.SP.cardnum);
				String requestJson = new Gson().toJson(descRequest);
				Map<String, String> map = new HashMap<String, String>();
				map.put(HttpUtil.PARAMS_KEY, requestJson);
				return map;
			}

			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				// TODO Auto-generated method stub
				String str = null;
				try {
					str = new String(response.data, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return Response.success(str,
						HttpHeaderParser.parseCacheHeaders(response));
			}
		};

		mRequestQueue.add(stringRequest);
	}

	@Override
	public void widgetClick(View view) {
		super.widgetClick(view);
		Contants.starTime = System.currentTimeMillis();
		switch (view.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.img_close:
			tipContent.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
}
